﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.DTO.User;
using BaseAuthRole.IService;
using BaseAuthRole.Web.Filters;
using Lotus.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Environment;
using RS.Tool.Base;

namespace BaseAuthRole.Web.Controllers
{
    [Route("[controller]/[action]")]
    [PageAuthCheckFilter]
    [RoleActionCheckFilter]
    public class UserManagerController : Controller
    {

        private IApplicationService _applictationService;

        private IUserService _userService;

        private IBaseLotusClient _baseLotusClient;
        public UserManagerController(IApplicationService applictationService, IUserService userService, IBaseLotusClient baseLotusClient)
        {

            this._applictationService = applictationService;
            this._userService = userService;
            this._baseLotusClient = baseLotusClient;

        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserDetail(string id)
        {
          
            var info = _userService.GetUIUser(id);

            if (info == null)
            {
                return Redirect(ConfigurationHelper.GetAppSettings("noresource_url"));
            }

            ViewData["user"] = info;

            return View();
        }
        public ActionResult UserEdit(string id)
        {
         

            if (!string.IsNullOrEmpty(id))
            {
                var info = _userService.GetUIUser(id);

                if (info == null)
                {


                }

                var user_role = _userService.GetCJWUserRoleRelation(id);

                ViewData["user"] = info;

                ViewData["user_role"] = user_role;
            }

            long count = 0;

            var roles = _userService.GetRoles(1, 9999, "", " \"CreateTime\"", out count, null);

            ViewData["roles"] = roles;

            return View();
        }

        #region 请求部分

        public string GetUserList(int pagenum,int pagesize,string para)
        {
            var result = new CommonResult();

            if (pagesize < 0)
            {

                pagesize = 1;
            }
            if (pagesize > 200)
            {
                pagesize = 200;

            }
            if (pagenum <= 0)
            {

                pagenum = 1;
            }

            long count = 0;

            var condition = "";

            Dictionary<string, object> obj = new Dictionary<string, object>();


            if (!string.IsNullOrEmpty(para))
            {
                obj.Add("para", $"%{para}%");
                condition = " \"Phone\" like @para or \"Name\" like @para";
            }
            var info = this._userService.GetUsers(pagenum, pagesize, condition, " \"CreateTime\" desc", out count, obj);

            var total_num = Math.Ceiling(count / (decimal)pagesize);


            result.IsError = false;
            result.Result = new
            {

                content = info,
                total_num = total_num

            };

            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string UpdateUser([FromForm]UpdateUserInput updateUserInput )
        {

            var result = new CommonResult();

            var id = updateUserInput.Id;

            var status = updateUserInput.Status;

            var info = this._userService.GetUIUser(id);

            if (info == null)
            {
                result.Message = "用户不存在";
                return JsonConvert.SerializeObject(result);
            }

            info.Status = status;

            this._userService.UpdateUIUser(info);

            result.IsError = false;

            return JsonConvert.SerializeObject(result);

        }


        [HttpPost]
        public string AddOrUpdateUser([FromForm] AddOrUpdateUserInput addOrUpdateUserInput)
        {

            var result = new CommonResult();
            var id = addOrUpdateUserInput.Id;

            var name = addOrUpdateUserInput.Name;

            var phone = addOrUpdateUserInput.Phone;

            var password = addOrUpdateUserInput.PassWord;

            var roles = string.IsNullOrEmpty(addOrUpdateUserInput.Roles)?null: addOrUpdateUserInput.Roles.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            var loginname = addOrUpdateUserInput.LoginName;

            var jobnumber = addOrUpdateUserInput.JobNumber;

            var title = addOrUpdateUserInput.Title;

            var jobtitle = addOrUpdateUserInput.JobTitle;

            var department = addOrUpdateUserInput.Department;

            var profession = addOrUpdateUserInput.Profession;           

            var roles_id = new List<string>();

            var roles_name = "";

            if (roles != null)
            {
                foreach (var o in roles)
                {
                    var temp = o.Split('_');
                    roles_id.Add(temp[0]);

                    roles_name += temp[1] + ",";
                }

                if (roles_name.Length > 0)
                {
                    roles_name = roles_name.Substring(0, roles_name.Length - 1);
                }
            }

            if (!string.IsNullOrEmpty(id))
            {

                var info = this._userService.GetUIUser(id);

                if (info == null)
                {
                    result.Message = "用户不存在";
                    return JsonConvert.SerializeObject(result);
                }

                info.Name = name;

              
                info.JobNumber = jobnumber;
                info.LoginName = loginname;
                info.Department = department;
                info.Title = title;
                info.JobTitle = jobtitle;
                info.Phone = phone;
                info.Profession = profession;

                if (!string.IsNullOrEmpty(password))
                {

                    info.PassWord = SecretHelper.GetMD5(password);

                }


                this._userService.UpdateUserRole(info, roles_id);

                result.IsError = false;

            }
            else
            {

                if (string.IsNullOrEmpty(phone))
                {

                    result.Message = "手机号不能为空";

                    return JsonConvert.SerializeObject(result);
                }

                if (string.IsNullOrEmpty(password))
                {

                    result.Message = "密码不能为空";

                    return JsonConvert.SerializeObject(result);
                }



                var info = new UUIUser
                {


                };

                info.Name = name;
                info.JobNumber = jobnumber;
                info.LoginName = loginname;
                info.PassWord = password;
                
                info.Department = department;
                info.Title = title;
                info.JobTitle = jobtitle;
                info.Phone = phone;
                info.Profession = profession;
                info.PassWord = SecretHelper.GetMD5(password);
                this._userService.CreateUser(info, roles_id);
                result.IsError = false;
            }

            return JsonConvert.SerializeObject(result);
        }

        #endregion

        #region

        
        #endregion

    }
}
